<template>
    <el-dialog v-model="KnowVisible" class="custom-dialog" :show-close='false' :close-on-click-modal="modalClose"
        modal-class="dialog-center" :width="width" :destroy-on-close="true" :style="{ width: `${width} !important` }"
        :before-close="handleClose">
        <div class="knowledge-info-header">
            <div class="title">{{ title || $t('message.buttons.newLib') }}</div>
            <svg class="close-icon" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="knowledge-info-body" v-loading="roleLoading">
            <el-form ref="knowFormRef" :model="knowForm" :rules="knowRules">
                <div class="form-item-title">{{ $t('message.text.cover') }}</div>
                <knowCover ref="knowCoverRef" :knowInfo="knowForm" @coverChange="coverChange"></knowCover>
                <div class="form-item-title">{{ $t('message.text.libName') }}</div>
                <el-form-item prop="name">
                    <el-input :placeholder="$t('message.placeholder.pleaseLibName')" v-model="knowForm.name"></el-input>
                </el-form-item>
                <div class="form-item-title">{{ $t('message.text.libDesc') }}</div>
                <el-form-item prop="description">
                    <el-input :placeholder="$t('message.placeholder.pleaseDesc')" v-model="knowForm.description"
                        type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
                </el-form-item>
                <template v-if="knowRole.length > 1">
                    <div class="form-item-title">{{ $t('message.text.libPermission') }}</div>
                    <div class="role-box">
                        <div class="role-item" v-for="(item, index) in roleList" :key="index" @click="changeRole(item)">
                            <svg class="icon">
                                <use
                                    v-bind:xlink:href="`#${knowForm.shareRole == item.value ? 'keowledge-mobile-xuanzhong' : 'keowledge-mobile-weixuanzhong'}`">
                                </use>
                            </svg>
                            <span>{{ item.label }}</span>
                        </div>
                    </div>
                </template>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
                <el-button type="primary" @click="submitKnow">{{ $t('message.buttons.submit') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter, useRoute } from "vue-router"
import knowCover from '@/views/knowSet/cover.vue'
const router = useRouter();
const route = useRoute();
import type { FormInstance, FormRules } from 'element-plus'
import { getKnowUserRole } from '@/api/role'
import { addLibrary } from '@/api/knowledge'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const emit = defineEmits([""])
const props = defineProps({
    width: {
        type: String,
        default: '547px'
    },
    remove: Function,
    callBack: Function,
    title: {
        type: String,
        default: ''
    },
    modalClose: {
        type: Boolean,
        default: false
    }
})
const KnowVisible = ref(false)
const knowFormRef = ref<FormInstance>()
const knowForm = ref({
    name: '',
    description: "",
    shareRole: 'user',
    color: ''
})
const roleList = ref([])
const roleLoading = ref(false)
const knowRole = ref([])
const knowRules = ref<FormRules>({
    name: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (!value) {
                    callback(new Error($t('message.placeholder.pleaseLibName')))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})
const knowledgeType = ref('')
const knowledgeId = ref('')
const knowleEditType = ref('')
const knowCoverRef = ref()
onMounted(() => {
    knowledgeId.value = route.params.id
    knowledgeType.value = route.params.type
})
function init() {
    roleList.value = [
        {
            label: $t('message.text.userDesc'),
            value: 'user'
        }]
    KnowVisible.value = true
    getKnowRole()
}
function handleClose() {
    roleList.value = [{
        label: $t('message.text.privateDesc'),
        value: 'user'
    }]
    knowCoverRef.value.clearCover()
    knowFormRef.value?.resetFields()
    KnowVisible.value = false
}

function getKnowRole() {
    roleLoading.value = true
    getKnowUserRole().then(res => {
        if (res.data.code == 0) {
            knowRole.value = res.data.data || []
            knowRole.value.forEach(item => {
                if (item == 'all') {
                    roleList.value.push({
                        label: $t('message.text.wholeNetworkDesc'),
                        value: 'all'
                    })
                }
                if (item == 'register') {
                    roleList.value.push({
                        label: $t('message.text.enterpriseDesc'),
                        value: 'register'
                    })
                }
            })
            roleList.value.sort((a, b) => {
                return a.order - b.order
            })
            roleLoading.value = false
        }
    }).catch(err => {
        roleLoading.value = false
    })
}
function changeRole(item) {
    knowForm.value.shareRole = item.value
}
function submitKnow() {
    knowFormRef.value.validate((valid) => {
        if (valid) {
            addLibrary({
                otherJSOn: JSON.stringify({ brisk: false, superWidth: false }),
                transfer: null,
                readNotify: true,
                ...knowForm.value
            }).then(res => {
                if (res.data.code == 0) {
                    proxy.$eventBus.$emit('refreshPage', res.data.data)
                    proxy.$eventBus.$emit('addList', knowledgeId.value ? 'my' : knowledgeType.value, res.data.data)
                    handleClose()
                    router.push({
                        path: `/knowledge/my/${res.data.data.id}`
                    })
                }
            })
        }
    })
}
function coverChange(form) {
    knowForm.value = {
        ...form,
        name: knowForm.value.name,
        shareRole: knowForm.value.shareRole,
        description: knowForm.value.description
    }
}
defineExpose({
    init
})
</script>
<style lang="scss">
.custom-dialog {
    .knowledge-info-header {
        height: 48px;
        background: #f5f6f7;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        color: #363B4C;
        @include SourceHanSansCN-Bold;
        padding: 0px 16px 0px 24px;

        .title {}

        .close-icon {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .knowledge-info-body {
        padding: 0px 24px 16px 32px;

        input::-webkit-input-placeholder {
            @include SourceHanSansCN-Regular;
        }

        textarea::-webkit-input-placeholder {
            @include SourceHanSansCN-Regular;
        }

        textarea {
            box-shadow: none;
            background: #f5f6f7;
            resize: none;
        }

        .el-input__wrapper {
            background: #F5F6F7 !important;
            box-shadow: none !important;

            input {
                height: 32px !important;
            }
        }

        .form-item-title {
            color: #363B4C;
            font-size: 14px;
            @include SourceHanSansCN-Bold;
            margin-bottom: 8px;
            margin-top: 16px;
        }

        .role-box {
            .role-item {
                cursor: pointer;
                display: flex;
                align-items: center;
                padding: 8px 0px;

                .icon {
                    width: 14px;
                    min-width: 14px;
                    height: 14px;
                    margin-right: 12px;
                }
            }
        }

    }

    .dialog-footer {
        height: 60px;
        padding: 0px 16px;
        display: flex;
        align-items: center;
        justify-content: end;
        border-top: 1px solid #eeeff0;
    }
}
</style>